<?php
include_once('../includes/definer.php');
include_once(INC.'admin/php/bootstrap.php');
include_once(INC.'admin/php/clases/FileImage.php');

if ($_POST['id']) {
     $gallery = Doctrine::getTable('gallery')->find($_POST['id']);
} else {
     $gallery = new Gallery();
     $gallery->orden = Gallery::lastOrden()+1;
}


//INFO

$photography = Doctrine::getTable('photography')->find($_POST['photography']);
$gallery->titulo = $_POST['titulo'];
$gallery->descripcion = $_POST['descripcion'];
$gallery->photography = $photography;

//IMAGENES
$n = (Imagen::lastId())?Imagen::lastId()+1:1;//numero al final de la imagen (Ej: imagen.1.jpg, imagen.2.jpg)
$origen = INC.'content/tmp/photography/'.$photography->uri.'/';
$destino = INC.'content/photography/'.$photography->uri.'/';
if (isset($_POST['newImages']) && count($_POST['newImages'])) {
    foreach ($_POST['newImages'] as $newImage) {
        $data = explode(',', $newImage);

        //Imagen thumbnail 220x147
        if (file_exists($origen.'thumbnail/'.$data[0].'.'.$data[2])) {
            if (copy($origen.'thumbnail/'.$data[0].'.'.$data[2], $destino.'thumbnail/'.$gallery->uri.'.'.$n.'.'.$data[2])) {
                unlink($origen.'thumbnail/'.$data[0].'.'.$data[2]);
            }
        } else {
            $fileImage = new FileImage($origen.$data[0].'.'.$data[2]);
            $fileImage->escalar(220, 147);
            $fileImage->recortarDesdeElCentro(220, 147);
            $fileImage->save($destino.'thumbnail/'.$gallery->uri.'.'.$n);
        }

        //Imagen  original
        if (copy($origen.$data[0].'.'.$data[2], $destino.$gallery->uri.'.'.$n.'.'.$data[2])) {
            unlink($origen.$data[0].'.'.$data[2]);
        }

        //Creo el objeto imagen y se lo asigno al producto
        $imagen = new Imagen();
        $imagen->src = $gallery->uri.'.'.$n.'.'.$data[2];
        $imagen->orden = $data[1];
        $gallery->imagenes[] = $imagen;
        $n++;
    }
}
$gallery->save();
header('location: '.URL.'admin/photography/'.$photography->uri);
?>
